#include <iostream>
#include <cstdlib>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <errno.h>
#include <string>
#include "Log.hpp"

void Usage(const std::string &proc)
{
    std::cout << "Usage: \n\t" << proc << " udpserver_ip udpserver_port" << std::endl;
}

// ./udpclient serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (socket < 0)
    {
        std::cout << "create socket fail: " << strerror(errno) << std::endl;
        return 2;
    }

    struct sockaddr_in serverinfo; // 填充服务端信息
    bzero(&serverinfo, 0);
    serverinfo.sin_family = AF_INET;
    serverinfo.sin_addr.s_addr = inet_addr(serverip.c_str());
    serverinfo.sin_port = htons(serverport);

    while (true)
    {
        std::string inbuffer;
        std::cout << "Please entry#:";
        std::getline(std::cin, inbuffer);
        ssize_t n = sendto(sockfd, inbuffer.c_str(), inbuffer.size(), 0, (struct sockaddr *)&serverinfo, sizeof serverinfo);
        if (n)
        {
            char buffer[1024];
            struct sockaddr_in temp;
            socklen_t len = sizeof temp;
            ssize_t m = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&temp, &len);
            if (m > 0)
            {
                buffer[m] = 0;
                // lg.LogMessage(Info, "%s %s", "Server say@", buffer);
                std::cout << "Server sry@: " << buffer << std::endl;
            }
            else
                break;
        }
        else
            break;
    }
    return 0;
}